package cn.vivi.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.vivi.domain.Classes;
import cn.vivi.service.ClassesService;
import cn.vivi.service.impl.ClassesServiceImpl;
import cn.vivi.util.JsonUtils;
import cn.vivi.util.Result;

@WebServlet("/classes")
@SuppressWarnings("all")
public class ClassesServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	private ClassesService classesService = new ClassesServiceImpl();

	private void initParamer(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf8");
		initParamer(request, response);
		String method = request.getParameter("method");
		if ("findAll".equals(method)) {
			this.findAll();
			return;
		}
		if ("add".equals(method)) {
			this.addClasses();
			return;
		}
		if ("delete".equals(method)) {
			this.deleteClasses();
			return;
		}
		if ("update".equals(method)) {
			this.updateClasses();
		}
	}

	private void updateClasses() {
		String name = request.getParameter("name");
		String id = request.getParameter("id");
		Classes classes = new Classes();
		classes.setName(name);
		classes.setId(Integer.parseInt(id));
		if (classesService.updateClasses(classes)) {
			JsonUtils.toJson(response, Result.success().setMessage("更新分类成功"));
		} else {
			JsonUtils.toJson(response, Result.error().setMessage("更新分类失败"));
		}

	}

	private void deleteClasses() {
		String id = request.getParameter("id");
		if (classesService.deleteClasses(id)) {
			JsonUtils.toJson(response, Result.success().setMessage("删除分类成功"));
		} else {
			JsonUtils.toJson(response, Result.error().setMessage("删除分类失败"));
		}
	}

	private void addClasses() {
		Classes classes = new Classes();
		classes.setName(request.getParameter("name"));
		if (classesService.addClasses(classes)) {
			JsonUtils.toJson(response, Result.success().setMessage("添加分类成功"));
		} else {
			JsonUtils.toJson(response, Result.error().setMessage("添加分类失败"));
		}
	}

	private void findAll() {
		List<Classes> classes = classesService.findAll();
		JsonUtils.toJson(response, Result.success().createMap().setData("items", classes));
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf8");
		doGet(request, response);
	}

}
